package com.gulimall.search.service.impl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.BulkResponse;
import co.elastic.clients.elasticsearch.core.bulk.BulkOperation;
import com.gulimall.common.to.SkuEsModel;
import com.gulimall.search.constant.EsConstant;
import com.gulimall.search.service.ElasticSaveService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author kkk
 * @date 2022/7/21
 */
@Service
@Slf4j
public class ElasticSaveServiceImpl implements ElasticSaveService {
    @Autowired
    ElasticsearchClient elasticsearchClient;

    @Override
    public boolean saveProduct(List<SkuEsModel> esModelList) throws IOException {
        List<BulkOperation> bulkOperations = new ArrayList<>();
        esModelList.forEach(item -> {
            BulkOperation operation =
                    new BulkOperation.Builder().index(i -> i.index(EsConstant.PRODUCT_INDEX_NAME).id(item.getSkuId().toString()).document(item)).build();
            bulkOperations.add(operation);
        });

        BulkResponse bulkResponse =
                elasticsearchClient.bulk(b -> b.index(EsConstant.PRODUCT_INDEX_NAME).operations(bulkOperations));
        System.out.println(bulkResponse);
        return bulkResponse.errors();
    }
}
